package uexec

import (
	"os/exec"
	"time"
)

/**
 support windows env
 !!!!!: params <= 4
 */
func ExecWinCmd(cmdText string, params []string, sleepTime int) (string, int) {
	timeout := make(chan bool, 1)
	ch := make(chan string, 1)

	var cmd *exec.Cmd
	paramNum := len(params)
	if paramNum == 0 {
		cmd = exec.Command("cmd", "/C", cmdText)
	} else if paramNum == 1 {
		cmd = exec.Command("cmd", "/C", cmdText, params[0])
	} else if paramNum == 2 {
		cmd = exec.Command("cmd", "/C", cmdText, params[0], params[1])
	} else if paramNum == 3 {
		cmd = exec.Command("cmd", "/C", cmdText, params[0], params[1], params[2])
	} else if paramNum == 4 {
		cmd = exec.Command("cmd", "/C", cmdText, params[0], params[1], params[2], params[3])
	} else {
		return "param num > 4", 1
	}

	var msgTimeout string
	go func() {
		out, err := cmd.CombinedOutput()
		if err != nil {
			ch <- err.Error()
		}
		msgTimeout = string(out)
		ch <- string(out)
	}()

	go func() {
		time.Sleep(time.Duration(sleepTime) * time.Second)
		timeout <- true
	}()

	select {
	case msg := <-ch:
		// ch 中读到数据
		return msg, 0
	case <-timeout:
		// 超时了
		cmd.Process.Kill()
		time.Sleep(3 * time.Second)
		// 过3秒后在获取执行结果数据
		if len(msgTimeout) == 0 {
			return "timeout error", 1
		}
		return "exec timeout, but get msg:" + msgTimeout, 1
	}
}


/**
 support linux env
 */
func ExecUnixCmd(cmdText string, sleepTime int) (string, int) {
	timeout := make(chan bool, 1)
	ch := make(chan string, 1)

	var cmd *exec.Cmd
	cmd = exec.Command("/bin/sh", "-c", cmdText)

	var msgTimeout string
	go func() {
		out, err := cmd.CombinedOutput()
		if err != nil {
			ch <- err.Error()
		}
		msgTimeout = string(out)
		ch <- string(out)
	}()

	go func() {
		time.Sleep(time.Duration(sleepTime) * time.Second)
		timeout <- true
	}()

	select {
	case msg := <-ch:
		// ch 中读到数据
		return msg, 0
	case <-timeout:
		// 超时了
		cmd.Process.Kill()
		time.Sleep(3 * time.Second)
		// 过3秒后在获取执行结果数据
		if len(msgTimeout) == 0 {
			return "timeout error", 1
		}
		return "exec timeout, but get msg:" + msgTimeout, 1
	}
}